// pages/goodsDetail/goodsDetail.js
const productService = require('../../../../api/productService.js')
const shopcartService = require('../../../../api/shopcartService.js')
const teamBuyService = require('../../../../api/teamBuyService.js')
const memberService = require('../../../../api/memberService.js')
const util = require('../../../../utils/utils.js')
const storeService = require('../../../../api/storeService.js')
const secKillService = require('../../../../api/seckillService.js')
const wxaUserService = require('../../../../api/wxaUserService.js')
const advanceSellService = require('../../../../api/advanceSellService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productPictures: [],
    name: '',
    goodsLabels: [],
    description: '',
    labels: [],
    productProperties: [],
    soldCount: '',
    sellPrice: '',
    originalPrice: '',
    productDetails: [],
    productPictures: [],
    isTeam: false,
    teamBuyList: [],
    countDownList: [],
    teamBuyTimeList: [],
    teamBuyLeaderPrice: '',
    teamMemberPrice: '',
    teamLeaderRecordId: '',
    teamMemberCount: 0,
    goodsList: [],
    shopCartNum: '0',
    balance: '0',
    secKillInfo: {},
    isSecKill: false,
    time: {},
    hasUserInfo: false,
    advanceSell: false,
    advanceSellInfo: {},
    storeId: '',
    activityId: '',
    frontPrice: '',
    advanceSellTime: {},
    endTime: '',
    modal: false,
    productNum: 1,
    groupModal: false,
    groupInfo: {},
    countDownTime: {},
    specifications: '',
    memberLimit: 9999,
    timeId: 0,
    groupTimeId: 0,
    groupListTime: 0,
    secKillTime: 0,
    orderNumber: 0,
    current: 1,
    goodType: 'normal',
    scoreInfo: {},
    member: {},
    score: 0,
    groupNumber: '零',
    commissionTotal: 0.00,
    phone: false,
    orderSelfScope: '',
    teamBuyingType: 'COMMON',
  },
  // 点击首页回到首页
  toHome: function () {
    wx.switchTab({
      url: '../../index/index/index'
    })
  },
  toShopCart: function () {
    wx.switchTab({
      url: '../shopcart/shopcart'
    })
  },
  // 改变当前的显示数
  swiperChange: function (e) {
    this.setData({
      current: e.detail.current + 1
    })
  },
  // 检查是否具有购买商品的资格
  checkQualification: function () {
    const that = this
    let postData = {
      activityId: that.data.activityId,
      productId: that.options.productId,
      storeId: that.data.storeId
    }
    console.log(postData)
    secKillService.checkQualification(postData).then(res => {
      console.log(res)
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 获取个人积分数据
  getMemberScore: function () {
    const that = this
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        this.setData({
          member: app.globalData.userInfo.member,
          isMember: true
        })
        memberService.getBalance(that.data.member.mobile).then(res => {
          console.log(res)
          that.setData({
            score: res
          })
        }).catch(e => {
          wx.showToast({
            title: e.message,
            icon: 'none',
            duration: 2000
          })
        })
      } else {}
    }
  },
  /**
   * 获取商品详情数据
   * @param storeId 门店id
   * @param productId 商品id或团购id
   * @param type 模块类型 secondkill(秒杀)  group(拼团)  normal(普通)  score(积分)
   * mobile 分享人标识
   */
  getGoodsDetails: function (storeId, productId, type) {
    const self = this
    console.log(storeId, productId, type)
    if (productId) {
      console.log("1")
      if (type === 'normal') {
        // 普通商品详情页
        console.log("----------普通商品----------")
        self.getDetails(storeId, productId)
      } else if (type === 'group') {
        // 团购
        self.setData({
          goodType: 'group'
        })
        console.log("----------团购商品----------")
        self.getTeamBuyGoodsDetails(storeId, productId)
      } else if (type === 'secondkill') {
        // 抢购
        self.setData({
          goodType: 'secondkill'
        })
        console.log("----------抢购商品----------")
        self.getSecKillGoodsDetails(self.options.activityId, productId, storeId)

      } else if (type === 'advanceSell') {
        self.setData({
          goodType: 'advanceSell'
        })
        console.log("----------预售商品----------")
        self.getAdvanceSellDetails(self.options.advanceId, productId)
      } else if (type === 'score') {
        // 普通商品详情页
        self.setData({
          goodType: 'score'
        })
        self.getDetails(storeId, productId)
        self.getMemberScore()
      } else {
        // 普通商品详情页
        self.getDetails(storeId, productId)
      }
      if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
        const mobile = self.options.mobile
        try {
          wx.setStorageSync('wj_sharingId', mobile)
        } catch (e) {}
      }
      if (app.globalData.userInfo) {
        if (app.globalData.userInfo.member) {
          this.queryShopcart()
        }
      }
    } else {}
  },
  // 记录会员访问门店
  recordVisitStore: function (storeId) {
    memberService.visitStore(storeId).then(res => {
      console.log(res)
    }).catch(e => {
      console.log(e.message)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if (options.scene) {
      // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
      const scene = decodeURIComponent(options.scene)
      let sceneArr = scene.split(',')
      console.log(scene, sceneArr)
      options.productId = sceneArr[0]
      this.options.productId = sceneArr[0]
      options.type = sceneArr[1]
      this.options.type = sceneArr[1]
    }
    const self = this
    self.getMemberUserInfo()
    self.checkMobile()
    try {
      wx.getStorage({
        key: 'wj_member',
        success: function (res) {
          self.setData({
            teamLeaderRecordId: res.data.id
          })
          return res.data.id
        }
      })
    } catch (error) {
      console.log(error.message)
    }
    console.log(options)
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        storeId: app.globalData.storeInfo.id
      })
      self.getGoodsDetails(app.globalData.storeInfo.id, options.productId, options.type)
      console.log("1")
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy
          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
              // 获取商品详情
              console.log("2")
              self.getGoodsDetails(tempAllStores[tempIndex].id, options.productId, options.type)
            } else {
              // 查询所有门店
              console.log("3")
              storeService.queryList().then(res => {
                var allStores = [];
                res.forEach(item => {
                  if (item.status === 'OPEN') {
                    allStores.push(item)
                  }
                });
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.getGoodsDetails(res.id, options.productId, options.type)
              })
            }
          } catch (e) {
            // Do something when catch error
          }
        }
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.storeInfo) {
      this.getGoodsDetails(app.globalData.storeInfo.id, this.options.productId, this.options.type)
    }
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.groupTimeId)
    clearTimeout(this.data.groupListTime)
    clearTimeout(this.data.secKillTime)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const that = this
    let imageArr = that.data.productPictures
    let image = 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png'
    if (imageArr.length > 0) {
      image = imageArr[0].url
    }
    console.log(this.options)
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      var pages = getCurrentPages() //获取加载的页面
      var currentPage = pages[pages.length - 1] //获取当前页面的对象
      var url = currentPage.route //当前页面url
      var options = currentPage.options //如果要获取url中所带的参数可以查看options
      console.log(url, options)
      let path = url + '?mobile=' + memberId
      for (const key in options) {
        if (options.hasOwnProperty(key)) {
          const ele = options[key];
          if (key !== 'mobile') {
            path = path + '&' + key + '=' + ele
          }
        }
      }
      console.log(path)
      return {
        title: '鲜丰水果，新鲜才好吃！',
        path: path,
        imageUrl: image,
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        title: '鲜丰水果，新鲜才好吃！',
        imageUrl: image,
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },

  addShopCart: function (val) {
    const that = this
    let loginStatus = this.checkAuth()
    if (loginStatus) {
      if (that.data.isSecKill) {
        let postData = {
          activityId: that.data.activityId,
          productId: that.options.productId,
          storeId: that.data.storeId
        }
        const limitCount = that.data.secKillInfo.limitCount
        secKillService.checkQualification(postData).then(res => {
          util.setHideLoading(true)
          that.addShopCartNew(val)
        }).catch(e => {
          console.log(e)
          if (e.code !== -99999) {
            wx.showToast({
              title: e.message,
              icon: 'none',
              duration: 2000
            })
          } else {
            that.handlePopupPhone()
          }
        })
      } else {
        that.addShopCartNew(val)
      }
    } else {}
  },
  addShopCartNew: function (val) {
    const that = this
    let balance = that.data.balance
    if (balance > 0) {
      console.log(val);
      var productId = val.detail.target.dataset.id;
      var postData = {
        storeId: that.data.storeId,
        lists: [{
          count: 1,
          productId: productId
        }]
      }
      if (that.data.goodType === 'newmbr') {
        postData.lists[0].newmbrActivityId = that.data.goodsDetail.activityId
      } else if (that.data.goodType === 'secondkill') {
        postData.lists[0].grabActivityId = that.data.activityId
      }
      if (app.globalData.userInfo.member) {
        try {
          wx.setStorageSync('wj_wxa_formId', val.detail.formId)
        } catch (e) {}
        shopcartService.cateringAdd(postData).then(res => {
          console.log(res)
          if (!util.isHideLoading()) {
            util.setHideLoading(true)
          }
          that.queryShopcart()
          wx.showToast({
            title: '添加购物袋成功~',
            icon: 'none',
            duration: 2000
          })
        }).catch(err => {
          console.log(err)
          if (that.data.goodType === 'newmbr' && err.code === 39008) {
            wx.showToast({
              title: '您已购买过专享商品~',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        this.handlePopupPhone()
      }
    } else {
      wx.showToast({
        title: '门店库存不足，换家门店试试吧~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 购物车查询
  queryShopcart: function () {
    var self = this
    shopcartService.getProductsCount().then(res => {
      wx.hideLoading()
      console.log(res)
      let allNum = res
      try {
        var storeInfo = wx.getStorageSync('wj_distributionStore')
        if (storeInfo) {
          shopcartService.getCatering(storeInfo.id).then(res => {
            console.log(res)
            if (util.isHideLoading()) {
              util.setHideLoading(false)
            }
            let productNum = 0
            if (res.items && res.items.length > 0) {
              res.items.forEach(item => {
                productNum += item.productNum
              })
            }
            self.setData({
              shopCartNum: allNum - productNum
            })
          }).catch(e => {
            self.setData({
              shopCartNum: allNum
            })
            if (util.isHideLoading()) {
              util.setHideLoading(false)
            }
          })
        } else {
          storeService.getDistributionStore().then(res => {
            console.log(res)
            if (res) {
              wx.setStorage({
                key: "wj_distributionStore",
                data: res
              })
              shopcartService.getCatering(storeInfo.id).then(res => {
                console.log(res)
                let productNum = 0
                if (res.items && res.items.length > 0) {
                  res.items.forEach(item => {
                    productNum += item.productNum
                  })
                }
                self.setData({
                  shopCartNum: allNum - productNum
                })
                if (util.isHideLoading()) {
                  util.setHideLoading(false)
                }
              }).catch(e => {
                self.setData({
                  shopCartNum: allNum
                })
                if (util.isHideLoading()) {
                  util.setHideLoading(false)
                }
              })
            } else {

            }
          })
          self.setData({
            shopCartNum: allNum
          })
        }
      } catch (e) {

      }

    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  hideTel: function (tel) {
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    tel = tel.replace(reg, "$1****$2");
    return tel
  },
  handleToTeamBuying: function (val) {
    const that = this
    console.log(val)
    let teamBuyId = val.target.dataset.teambuyid
    let teamLeaderRecordId = val.target.dataset.teamleaderrecordid
    wx.navigateTo({
      url: '../../fightGroup/groupPurchase/groupPurchase?teamBuyId=' + teamBuyId + '&teamLeaderRecordId=' + teamLeaderRecordId
    })
  },
  toAllTeamList: function () {
    wx.navigateTo({
      url: '../../fightGroup/teamList/teamList?goodsId=' + this.data.goodsId + '&storeId=' + this.data.storeId + '&teamBuyId=' + this.options.productId
    })
  },

  clickBlank: function (val) {
    if (val.currentTarget.dataset.type === 'goods') {
      this.setData({
        modal: false
      })
    } else if (val.currentTarget.dataset.type === 'group') {
      this.setData({
        groupModal: false
      })
    }

  },
  clickBody: function () {

  },

  // 数量减事件
  handleReduce: function (e) {
    const that = this
    let num = that.data.productNum
    if (num > 1) {
      num--
      that.setData({
        productNum: num
      })
    } else {

    }
  },
  // 数量加事件
  handleAdd: function (e) {
    const that = this
    let num = that.data.productNum
    let limit = that.data.memberLimit
    const orderNumber = that.data.orderNumber
    let name = that.data.name
    if (num < that.data.balance) {
      if (that.data.advanceSell) {
        if (num < limit) {
          num++
          that.setData({
            productNum: num
          })
        } else {
          wx.showToast({
            title: '该商品预售活动最多只能购买' + limit + '件~',
            icon: 'none',
            duration: 2000
          })
        }
      } else if (that.data.isTeam) {
        if (num < orderNumber) {
          num++
          that.setData({
            productNum: num
          })
        } else {
          wx.showToast({
            title: '该商品团购活动最多只能购买' + orderNumber + '件~',
            icon: 'none',
            duration: 2000
          })
        }
      }
    } else {
      wx.showToast({
        title: '我们只有这么多了~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  handleInput: function (e) {
    const that = this
    let limit = 999
    let num = e.detail.value
    const balance = that.data.balance
    if (that.data.advanceSell) {
      limit = that.data.memberLimit
    } else if (that.data.isTeam) {
      limit = that.data.orderNumber
    }
    if (num < balance) {
      if (num < limit) {
        that.setData({
          productNum: num
        })
      } else {
        that.setData({
          productNum: limit
        })
        if (that.data.isTeam) {
          wx.showToast({
            title: '该商品团购活动最多只能购买' + limit + '件~',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '该商品预售活动最多只能购买' + limit + '件~',
            icon: 'none',
            duration: 2000
          })
        }
      }
    } else {
      if (num < limit) {
        this.setData({
          productNum: balance
        })
        wx.showToast({
          title: '我们只有这么多了~',
          icon: 'none',
          duration: 2000
        })
      } else {
        if (balance < limit) {
          this.setData({
            productNum: balance
          })
          wx.showToast({
            title: '我们只有这么多了~',
            icon: 'none',
            duration: 2000
          })
        } else {
          this.setData({
            productNum: limit
          })
          if (that.data.isTeam) {
            wx.showToast({
              title: '该商品团购活动最多只能购买' + limit + '件~',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '该商品预售活动最多只能购买' + limit + '件~',
              icon: 'none',
              duration: 2000
            })
          }
        }
      }
    }
  },
  // 前往下单
  scoreExchange: function (val) {
    const that = this
    var good = that.data.scoreInfo
    console.log(good)
    if (that.data.balance > 0) {
      if (that.data.score > good.exchangeScores) {
        try {
          let scoreMall = {
            allPrice: good.sellPrice,
            storeId: this.data.storeId,
            goodsList: [],
            orderType: 'scoreMall',
            score: good.exchangeScores,
            scource: 'BUYNOW'
          }
          let tempData = {
            ...good,
            productId: good.id,
            productNum: 1,
            sellPrice: good.sellPrice,
          }
          scoreMall.goodsList.push(tempData)
          console.log(scoreMall)
          wx.setStorageSync('wj_shopcart', scoreMall)
        } catch (e) {
          console.log(e)
        }
        // 判断是否绑定手机号
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          that.handlePopupPhone()
        }
      } else {
        wx.showToast({
          title: '积分不足',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '您来晚了，商品已售空',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 下一步
  handleNext: function () {
    const that = this
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.member) {
        that.setData({
          modal: true
        })
      } else {
        that.handlePopupPhone()
      }
    }
  },
  // 参加千人团
  joinThousandGroup: function () {
    const that = this
    let teamBuyList = this.data.teamBuyList
    if (teamBuyList.length > 0) {
      console.log(teamBuyList)
      var newArr = [];
      newArr = [].concat(teamBuyList); // newArr为一个新的数组，不是简单的赋值引用
      function compare(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value2 - value1;
        }
      }
      newArr.sort(compare('overplusJoinCount')); // newArr已经按照从大到小的顺序进行排列, 根据对象中的overplusJoinCount属性进行排序
      console.log(newArr)
      let joinTeam = newArr[0]
      this.getOpenTeamBuyData(joinTeam.teamBuyId, joinTeam.teamLeaderRecordId)
    } else {
      wx.showToast({
        title: "没有进行中的团购活动~",
        icon: 'none'
      })
    }

  },
  // 一起拼团
  openTeamBuyModal: function (val) {
    var teamBuyId = val.currentTarget.dataset.teambuyid
    var teamLeaderRecordId = val.currentTarget.dataset.teamleaderrecordid
    this.getOpenTeamBuyData(teamBuyId, teamLeaderRecordId)
  },
  /**
   * 获取某一拼团的数据
   * @param teamBuyId 团购活动id
   * @param teamLeaderRecordId 团长记录id
   */
  getOpenTeamBuyData: function (teamBuyId, teamLeaderRecordId) {
    const self = this
    teamBuyService.getDetails(teamBuyId, teamLeaderRecordId).then(res => {
      console.log(res)
      let tempData = {
        ...res,
        teamLeaderPrice: res.teamLeaderPrice ? res.teamLeaderPrice : res.teamMemberPrice,
        joinMemberCount: res.joinMemberCount ? res.joinMemberCount : 0,
        leaderImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        teamMemberImageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
        teamBuyEnd: false
      }
      self.setData({
        groupInfo: tempData
      })
      var data = new Date()
      var nowDate = new Date().getTime();
      let openTime = 0
      if (self.data.groupInfo.openTeamTime) {
        openTime = new Date(self.data.groupInfo.openTeamTime.replace(/-/g, '/')).getTime()
      } else {
        openTime = nowDate
        self.setData({
          openTeamTime: (util.formatTime(data)).replace(/\//g, '-')
        })
        console.log(self.data.groupInfo.openTeamTime)
      }
      let duration = (nowDate - openTime) / 1000
      if (duration >= self.data.groupInfo.duration) {
        let newTempData = {
          ...tempData,
          teamBuyEnd: true
        }
        self.setData({
          groupInfo: newTempData
        });
      }
      if (self.data.groupInfo.teamBuyEnd === false) {
        // 获取倒计时
        let teamBuyTimeInfo = [];
        // 将活动的结束时间参数提成一个单独的数组，方便操作
        let tempTime = {
          openTeamTime: this.data.groupInfo.openTeamTime,
          duration: this.data.groupInfo.duration
        }
        teamBuyTimeInfo.push(tempTime)
        this.setData({
          teamBuyTimeList: teamBuyTimeInfo
        });
        clearTimeout(self.data.timeId)
        countDown()
        // 执行倒计时函数
        function countDown() {
          clearTimeout(self.data.timeId)
          self.setData({
            countDownTime: util.countDown(teamBuyTimeInfo)[0]
          })
          // console.log(self.data.countDownTime)
          if (self.data.countDownTime.hou == '00' && self.data.countDownTime.min == '00' && self.data.countDownTime.sec == '00') {
            let newData = {
              ...tempData,
              teamBuyEnd: true
            }
            self.setData({
              groupInfo: newData
            });
          }
          var time = setTimeout(
            function () {
              countDown(teamBuyTimeInfo);
            }, 1000)
          self.setData({
            timeId: time
          })
        }
      } else {

      }
    })
    this.setData({
      groupModal: true
    })
  },
  // 参团
  joinGroup: function () {
    var self = this
    const loginStatus = this.checkAuth()
    if (loginStatus) {
      let goodsList = []
      goodsList.push(self.data.groupInfo.productDetails)
      let teamBuy = {
        goodsPrice: self.data.groupInfo.teamMemberPrice,
        storeId: self.data.storeId,
        storeName: self.data.storeName,
        goodsList: [],
        teamBuyId: self.data.groupInfo.id,
        teamLeaderRecordId: self.data.groupInfo.teamLeaderRecordId,
        orderType: 'group',
        teamBuyInfo: {
          endTime: self.data.groupInfo.endTime,
          orderSelfScope: self.data.groupInfo.orderSelfScope
        },
        scource: 'BUYNOW'
      }
      goodsList.forEach(item => {
        item = {
          ...item,
          productId: item.id,
          productNum: 1,
          sellPrice: self.data.sellPrice
        }
        console.log(item)
        teamBuy.goodsList.push(item)
      })
      console.log(teamBuy)
      wx.setStorageSync('wj_shopcart', teamBuy)
      if (self.data.teamMemberCount - self.data.joinMemberCount == 0) {

      } else {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          self.handlePopupPhone()
        }
      }
    } else {

    }
  },
  // 开团
  toPayTeamBuying: function (val) {
    var self = this
    const loginStatus = this.checkAuth()
    console.log(loginStatus)
    if (loginStatus && self.data.productNum != '' && self.data.productNum != 0) {
      if (self.data.balance > 0) {
        try {
          let goodsPrice = (self.data.teamBuyLeaderPrice * self.data.productNum).toFixed(2)
          let teamBuy = {
            goodsPrice: goodsPrice,
            storeId: self.data.storeId,
            goodsList: [],
            teamBuyId: self.options.productId,
            orderType: 'group',
            teamBuyInfo: {
              endTime: self.data.endTime,
              orderSelfScope: self.data.orderSelfScope
            },
            scource: 'BUYNOW'
          }
          let productsList = self.data.goodsList
          let sellPrice = (self.data.teamBuyLeaderPrice * self.data.productNum).toFixed(2)
          productsList.forEach(item => {
            console.log(item.productDetails)
            item = {
              ...item,
              productId: item.id,
              productNum: self.data.productNum,
              sellPrice: sellPrice,
            }
            if (item.sellEndTime && item.sellStartTime) {
              item = {
                ...item,
                startTime: item.sellStartTime,
                endTime: item.sellEndTime,
              }
            }
            console.log(item)
            teamBuy.goodsList.push(item)
          })
          console.log(teamBuy)
          wx.setStorageSync('wj_shopcart', teamBuy)
        } catch (e) {
          console.log(e.message)
        }
        // 判断是否绑定手机号
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          self.handlePopupPhone()
        }
      } else {
        wx.showToast({
          title: '拼团商品库存不足，看看其他拼团吧~',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      if (self.data.productNum != '' && self.data.productNum != 0) {
        wx.showToast({
          title: '请输入商品数量',
          icon: 'none',
          duration: 2000
        })
      } else {

      }
    }
  },
  // 抢购
  toPaySecKill: function (e) {
    const that = this
    console.log(that.options.productId)
    if (that.data.secKillInfo.availableStockAmount !== 0) {
      let postData = {
        activityId: that.data.activityId,
        productId: that.options.productId,
        storeId: that.data.storeId
      }
      console.log(postData)
      let loginStatus = this.checkAuth()
      if (loginStatus) {
        secKillService.checkQualification(postData).then(res => {
          console.log(res)
          if (that.data.balance > 0) {
            if (that.data.secKillInfo.availableStockAmount > 0) {
              try {
                let secKill = {
                  allPrice: this.data.secKillInfo.price,
                  storeId: this.data.storeId,
                  goodsList: [],
                  orderType: 'secondkill',
                  scource: 'BUYNOW'
                }
                let productsList = this.data.goodsList
                console.log(this.data.goodsList)
                productsList.forEach(item => {
                  item = {
                    ...item,
                    productId: item.id,
                    productNum: 1,
                    sellPrice: this.data.secKillInfo.price,
                    activityId: this.data.activityId,
                  }
                  console.log(item)
                  secKill.goodsList.push(item)
                })
                console.log(secKill)
                wx.setStorageSync('wj_shopcart', secKill)
              } catch (e) {}
              // 判断是否绑定手机号
              wx.navigateTo({
                url: '../../order/perfectOrder/perfectOrder'
              })
            } else {
              wx.showToast({
                title: '您来晚了，已经被抢光了~',
                icon: 'none',
                duration: 2000
              })
            }
          } else {
            wx.showToast({
              title: '门店正在努力补货中~',
              icon: 'none',
              duration: 2000
            })
          }
        }).catch(e => {
          if (e.code !== -99999) {
            wx.showToast({
              title: e.message,
              icon: 'none',
              duration: 2000
            })
          } else {
            that.handlePopupPhone()
          }
        })
      } else {}
    }
  },
  // 检查手机号
  checkMobile: function () {
    const self = this
    wx.getStorage({
      key: 'wj_member',
      success: function (res) {
        self.setData({
          hasUserInfo: true
        })
      },
      fail: function (error) {
        if (error) {
          self.setData({
            hasUserInfo: false
          })
        }
      }
    })
  },
  // 检查当前用户登录授权状态
  checkAuthStatus: function () {
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    var self = this;
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请同意授权获取用户信息',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            try {
              // 缓存页面参数信息，跳转授权页面
              let pageUrl = '../../goods/goodsDetail/goodsDetail?productId=' + self.options.productId + '&type=' + self.options.type
              if (self.options.activityId) {
                pageUrl = pageUrl + '&goodsList=' + self.options.goodsList + '&timeData=' + self.options.timeData + '&activityId=' + self.options.activityId
              }
              if (self.options.mobile) {
                pageUrl = pageUrl + '&mobile=' + self.options.mobile
              }
              wx.setStorageSync('wj_pageUrl', pageUrl)
            } catch (e) {
              console.log(e.message)
            }
            wx.switchTab({
              url: '../../member/my/my'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    } else {
      return true;
    }
  },
  /**
   * 通过接口获取团购商品详情数据
   * @param {string} storeId 门店id
   * @param {string} productId 团购活动id
   */
  getTeamBuyGoodsDetails(storeId, productId) {
    const self = this
    console.log(storeId, productId)
    teamBuyService.getGoodsDetails(productId).then(res => {
      console.log(res)
      if (res) {
        let tempData = []
        tempData.push(res.productDetails)
        this.setData({
          isTeam: true,
          teamBuyLeaderPrice: res.teamLeaderPrice ? res.teamLeaderPrice : res.teamMemberPrice,
          teamMemberPrice: res.teamMemberPrice,
          teamMemberCount: res.teamMemberCount,
          goodsList: tempData,
          name: res.productDetails.name,
          balance: res.productDetails.balance ? res.productDetails.balance : 0,
          description: res.productDetails.description ? res.productDetails.description : '',
          soldCount: res.productDetails.soldCount,
          sellPrice: res.teamLeaderPrice ? res.teamLeaderPrice : res.teamMemberPrice,
          originalPrice: res.productDetails.originalPrice ? res.productDetails.originalPrice : '',
          labels: res.productDetails.labels,
          productProperties: res.productDetails.productProperties,
          productDetails: res.productDetails.productDetails,
          productPictures: res.productDetails.productPictures,
          imageUrl: res.productDetails.imageUrl,
          goodsId: res.productDetails.id,
          endTime: res.endTime,
          orderNumber: res.teamMemberJoinCount ? res.teamMemberJoinCount : 999,
          groupNumber: util.numberConversion.numberToChinese(res.teamMemberCount),
          orderSelfScope: res.orderSelfScope,
          teamBuyingType: res.teamBuyingType
        })
        // 获取团购活动倒计时
        let startTime = res.startTime
        let endTime = res.endTime
        let startTimeStamp = new Date(startTime.replace(/-/g, '/')).getTime()
        let endTimeStamp = new Date(endTime.replace(/-/g, '/')).getTime()
        let duration = (endTimeStamp - startTimeStamp) / 1000
        let tempArr = []
        tempArr.push({
          openTeamTime: startTime,
          duration: duration
        })
        countDown()
        // 执行倒计时函数
        function countDown() {
          clearTimeout(self.data.groupTimeId)
          self.setData({
            groupTime: util.countDownDay(tempArr)[0]
          })
          var time = setTimeout(
            function () {
              countDown(tempArr);
            }, 1000)
          self.setData({
            groupTimeId: time
          })
        }
        // 获取商品库存
        const goodsId = res.productDetails.id
        productService.getDetails(self.data.storeId, goodsId).then(res => {
          console.log(res)
          self.setData({
            balance: res.balance //重设库存
          })
          // 商品规格
          if (res.productProperties.length > 0) {
            for (let i = 0; i < res.productProperties.length; i++) {
              const ele = res.productProperties[i];
              if (ele.propertyName === '规格') {
                self.setData({
                  specifications: ele.propertyValue
                })
                break
              }
            }
          }
        })
        self.getTeamBuyInfo(storeId, goodsId, productId)
      } else {
        self.getDetails(storeId, productId)
      }
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 获取开团信息
  getTeamBuyInfo: function (storeId, goodsId, teamBuyId) {
    const self = this
    teamBuyService.getOpenTeamBuyings(storeId, goodsId, teamBuyId).then(res => {
      if (res != '') {
        let tempGroupList = []
        res.forEach(item => {
          let teamBuyingStatus = item.teamBuyingStatus //团购活动状态：UNOPENED未开时/STARTED进行中/FINISHED已结束

          if (teamBuyingStatus === "STARTED") {
            let tempItem = {
              teamBuyId: item.id,
              teamLeaderRecordId: item.teamLeaderRecordId, //团长记录ID
              headPortrait: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/userImg1.png',
              creatorName: item.creatorName ? item.creatorName : '', //创建人名称
              mobile: this.hideTel(item.mobile),
              openTeamTime: item.openTeamTime, //开团时间
              duration: item.duration, //持续时间
              joinMemberCount: item.joinMemberCount, //参加人数
              status: item.status, //状态： 正常NORMAL,已删除 DELETED
              teamLeaderPrice: item.teamLeaderPrice, //团长价格
              teamMemberCount: item.teamMemberCount, //团购人数限定
              overplusJoinCount: item.teamMemberCount - item.joinMemberCount, //剩余参加人数
              teamMemberJoinCount: item.teamMemberJoinCount, //每人活动参加次数限制
              teamMemberPrice: item.teamMemberPrice //团员价格
            }
            tempGroupList.push(tempItem)
            // 获取用户头像
          }
        });
        this.setData({
          teamBuyList: tempGroupList,
        })
        // 获取倒计时
        let teamBuyTimeInfo = [];
        // 将活动的结束时间参数提成一个单独的数组，方便操作
        this.data.teamBuyList.forEach(o => {
          let tempTime = {
            openTeamTime: o.openTeamTime,
            duration: o.duration,
            id: o.teamLeaderRecordId
          }
          teamBuyTimeInfo.push(tempTime)
        })
        this.setData({
          teamBuyTimeList: teamBuyTimeInfo
        });
        countDown()
        // 执行倒计时函数
        function countDown() {
          clearTimeout(self.data.groupListTime)
          if (self.data.teamBuyList.length > 0) {
            let tempGroupInfo = self.data.teamBuyTimeList
            let countDownArr = util.countDown(teamBuyTimeInfo)
            let count = 0
            let tempList = self.data.teamBuyList
            let newTempList = []
            let newTempInfo = []
            let isDelete = false
            countDownArr.forEach(time => {
              tempList[count].time = time
              count++
            })
            tempList.forEach((item, j) => {
              if (item.time.hou == 0 && item.time.min == 0 && item.time.sec == 0) {
                for (let i = 0; i < tempGroupInfo.length; i++) {
                  const ele = tempGroupInfo[i];
                  if (ele.id === item.teamLeaderRecordId) {
                    newTempInfo = removeAaary(tempGroupInfo, ele)
                    isDelete = true
                    break
                  }
                }
              } else {
                newTempList.push(item)
              }
            })
            if (isDelete) {
              teamBuyTimeInfo = newTempInfo
              self.setData({
                teamBuyList: newTempList,
                teamBuyTimeList: newTempInfo
              })
            }
            self.setData({
              teamBuyList: newTempList,
            })
            var time = setTimeout(
              function () {
                countDown();
              }, 1000)
            self.setData({
              groupListTime: time
            })
          }
        }
        /*删除数组中的某一个对象
         *_arr:数组
         *_obj:需删除的对象
         */
        function removeAaary(_arr, _obj) {
          var length = _arr.length;
          for (var i = 0; i < length; i++) {
            if (_arr[i] == _obj) {
              if (i == 0) {
                _arr.shift(); //删除并返回数组的第一个元素
                return _arr;
              } else if (i == length - 1) {
                _arr.pop(); //删除并返回数组的最后一个元素
                return _arr;
              } else {
                _arr.splice(i, 1); //删除下标为i的元素
                return _arr;
              }
            }
          }
        }
      }

    }).catch(e => {
      console.log(e.message)
    })
  },
  // 获取商品详情
  getDetails: function (storeId, productId) {
    const self = this
    productService.getDetails(storeId, productId).then(res => {
      console.log(res)
      let tempData = []
      tempData.push(res)
      this.setData({
        goodsList: tempData,
        name: res.name,
        balance: res.balance,
        description: res.description ? res.description : '',
        soldCount: res.soldCount,
        sellPrice: res.sellPrice ? res.sellPrice : '',
        originalPrice: res.originalPrice ? res.originalPrice : '',
        labels: res.labels,
        productProperties: res.productProperties,
        productDetails: res.productDetails,
        productPictures: res.productPictures,
        goodsId: res.id,
        commissionTotal: res.backCashRate ? (parseFloat(res.sellPrice * res.backCashRate)).toFixed(2) : 0.00
      })
      if (res.business === 'SCORE') {
        this.setData({
          scoreInfo: res
        })
      }
      // 判断统配商品
      if (res.business === "DISTRIBUTION") {
        storeService.getDistributionStore().then(res => {
          console.log(res)
          return productService.getDetails(res.id, self.options.productId)
        }).then(res => {
          console.log(res)
          if (res) {
            self.setData({
              balance: res.balance //重设库存
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
      // 判断秒杀
      if (self.options.type === 'secondkill' && self.options.goodsList) {
        let secKillData = JSON.parse(self.options.goodsList)
        console.log(secKillData)
        secKillData.forEach(item => {
          if (productId === item.productId) {
            const secKillBalance = item.availableStockAmount
            const goodsBalance = res.balance
            if (goodsBalance < secKillBalance) {
              self.setData({
                balance: goodsBalance
              })
            } else {
              self.setData({
                balance: secKillBalance
              })
            }
          }
        })
      }
      // 商品规格
      if (res.productProperties.length > 0) {
        for (let i = 0; i < res.productProperties.length; i++) {
          const ele = res.productProperties[i];
          if (ele.propertyName === '规格') {
            self.setData({
              specifications: ele.propertyValue
            })
            break
          }
        }
      }
      // 商品标签
      let tempLabels = []
      if (res.labels.length > 0) {
        for (let i = 0; i < res.labels.length; i++) {
          const ele = res.labels[i];
          if (ele.type === 'PROMOTIONLABEL') {
            tempLabels.push(ele)
          }
        }
      }
      self.setData({
        goodsLabels: tempLabels
      })
      if (self.options.type === 'newmbr' && self.options.goodsDetail) {
        const goodsDetail = JSON.parse(self.options.goodsDetail)
        console.log(goodsDetail)
        self.setData({
          'goodsDetail': goodsDetail,
          'sellPrice': goodsDetail.price,
          'goodType': 'newmbr'
        })
      }
    })
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  getSecKillGoodsDetails: function (activityId, productId, storeId) {
    const that = this
    that.getDetails(storeId, productId)
    secKillService.getActivityStoreProduct(activityId, productId, storeId).then(res => {
      console.log(res)
      that.setData({
        activityId: res.activityId
      })
      let tempSecKillInfo = res.product
      let timeData = {
        startTime: res.startTime,
        endTime: res.endTime
      }
      that.getSecKillInfo(storeId, productId, tempSecKillInfo, timeData)
    }).catch(err => {
      console.log(err)
    })
  },
  // 查找是否秒杀商品
  getSecKillList: function (storeId, productId) {
    console.log(this.options)
    const that = this
    that.getDetails(storeId, productId)
    let SecKillGoodsList = []
    if (that.options.goodsList) {
      SecKillGoodsList = JSON.parse(that.options.goodsList)
    }
    if (SecKillGoodsList.length > 0) {
      console.log(SecKillGoodsList)
      let tempSecKillInfo = null;
      let activityId = null;
      SecKillGoodsList.forEach(item => {
        if (productId === item.productId) {
          tempSecKillInfo = item
          activityId = item.activityId
          that.setData({
            activityId: item.activityId
          })
        }
      })
      let postData = {
        page: 1,
        pageSize: 0,
        stateIn: 'STARTED',
        storeIdEquals: storeId
      }
      secKillService.query(postData).then(res => {
        let timeData = ''
        for (let i = 0; i < res.records.length; i++) {
          if (activityId != '') {
            for (let k = 0; k < res.records.length; k++) {
              const item = res.records[k];
              if (item.id === activityId) {
                timeData = {
                  startTime: item.startTime,
                  endTime: item.endTime
                }
              }
            }
          }
        }
        that.getSecKillInfo(storeId, productId, tempSecKillInfo, timeData)
      })
    } else {
      let postData = {
        page: 1,
        pageSize: 0,
        stateIn: 'STARTED',
        storeIdEquals: storeId
      }
      secKillService.query(postData).then(res => {
        console.log(res)
        let activityId = ''
        let timeData = ''
        let tempSecKillInfo = ''
        for (let i = 0; i < res.records.length; i++) {
          for (let j = 0; j < res.records[i].products.length; j++) {
            const item = res.records[i].products[j];
            if (item.productId == productId) {
              console.log(item)
              tempSecKillInfo = item
              activityId = item.activityId
              that.setData({
                activityId: activityId
              })
            }
          }
          if (activityId != '') {
            for (let k = 0; k < res.records.length; k++) {
              const item = res.records[k];
              if (item.id === activityId) {
                timeData = {
                  startTime: item.startTime,
                  endTime: item.endTime
                }
              }
            }
          }
        }
        console.log(timeData)
        console.log(tempSecKillInfo)
        if (timeData !== '' && tempSecKillInfo !== '') {
          that.getSecKillInfo(storeId, productId, tempSecKillInfo, timeData)
        }
      }).catch(e => {
        console.log(e.message)
      })
    }
  },
  // 获取商品秒杀信息
  getSecKillInfo: function (storeId, productId, secKillInfo, timeArray) {
    const self = this
    console.log(self.options)
    const loginStatus = self.checkAuthStatus()
    let secKillData = {}
    const timeData = timeArray
    self.setData({
      secKillInfo: secKillInfo
    })
    console.log(secKillData)
    let newStartTime = new Date(timeData.startTime.replace(/-/g, '/')).getTime()
    let newEndTime = new Date(timeData.endTime.replace(/-/g, '/')).getTime()
    let duration = (newEndTime - newStartTime) / 1000
    //var data = new Date()
    var nowDate = new Date().getTime();
    let countDownTime = (nowDate - newEndTime) / 1000 //获取当前时间与抢购活动结束时间的时间差
    if (countDownTime >= 0) {
      let tempSecKillInfo = {
        ...self.data.secKillInfo,
        secKillStatus: 'end'
      }
      self.setData({
        secKillInfo: tempSecKillInfo
      })
    } else {
      let tempSecKillInfo = {
        ...self.data.secKillInfo,
        secKillStatus: 'normal'
      }
      self.setData({
        secKillInfo: tempSecKillInfo
      })
    }
    // 获取倒计时
    let timeInfo = [];
    // 将活动的结束时间参数提成一个单独的数组，方便操作
    let tempTime = {
      openTeamTime: timeData.startTime,
      duration: duration
    }
    timeInfo.push(tempTime)
    countDown()
    // 执行倒计时函数
    function countDown() {
      clearTimeout(self.data.secKillTime)
      let countDownArr = util.countDown(timeInfo)
      self.setData({
        time: {
          hour: countDownArr[0].hou,
          minute: countDownArr[0].min,
          second: countDownArr[0].sec,
        },
        isSecKill: true
      })
      if (self.data.time.hour == '00' && self.data.time.minute == '00' && self.data.time.second == '00') {
        let tempSecKillInfo = {
          ...self.data.secKillInfo,
          secKillStatus: 'end'
        }
        self.setData({
          secKillInfo: tempSecKillInfo
        })
      }
      let time = setTimeout(
        function () {
          countDown();
        }, 1000)
      self.setData({
        secKillTime: time
      })
    }
    console.log(self.data.secKillInfo)
    // if (loginStatus) {
    //   this.checkQualification()
    // }
  },
  /**
   * 预售相关
   */
  getAdvanceSellDetails: function (advanceId, productId) {
    const that = this
    advanceSellService.getByIds(advanceId, productId).then(res => {
      console.log(res)
      console.log(res.product)
      let tempData = {
        ...res,
        advanceAmount: res.advanceAmount ? res.advanceAmount : 999,
        advanceId: advanceId
      }
      let newTempData = {}
      let balancePrice = res.balancePrice
      that.setData({
        advanceSell: true,
        balance: res.advanceAmount ? res.advanceAmount : 999,
        sellPrice: res.sellPrice,
        frontPrice: res.frontPrice,
      })
      let tempProductData = []
      tempProductData.push(res.product)
      this.setData({
        goodsList: tempProductData,
        name: res.product.name,
        description: res.product.description ? res.product.description : '',
        labels: res.product.labels,
        productProperties: res.product.productProperties,
        productDetails: res.product.productDetails,
        productPictures: res.product.productPictures,
        originalPrice: res.product.originalPrice,
        soldCount: res.product.soldCount,
        goodsId: res.product.id,
        imageUrl: res.product.imageUrl ? res.product.imageUrl : '',
        memberLimit: res.memberLimit ? res.memberLimit : 9999
      })

      function timeToArray(time) {
        const timeArray = time.split(' ')
        const timeList = timeArray[0].split('-')
        const newTime = timeList[1] + '月' + timeList[2] + '日'
        return newTime
      }

      function addDay(curDate, days) {
        return new Date((curDate / 1000 + (86400 * days)) * 1000)
      }
      let frontStartTime = timeToArray(tempData.frontStartTime)
      let frontEndTime = timeToArray(tempData.frontEndTime)
      let balanceStartTime = ''
      let balanceEndTime = ''
      let deliverTime = ''
      if (tempData.payType === 'PARTIAL') {
        balanceStartTime = timeToArray(tempData.balanceStartTime)
        balanceEndTime = timeToArray(tempData.balanceEndTime)
        const endTime = new Date(tempData.balanceEndTime.replace(/-/g, '/')).getTime()
        const tempEndTime = util.formatTime(addDay(endTime, tempData.deliveryTime))
        const newEndTime = tempEndTime.replace(/\//g, '-')
        deliverTime = timeToArray(newEndTime)
      } else {
        tempData = {
          ...tempData,
          balancePrice: 0
        }
        balancePrice = 0
      }
      console.log(frontStartTime, frontEndTime, balanceStartTime, balanceEndTime)
      that.setData({
        advanceSellInfo: tempData,
        advanceSellTime: {
          frontStartTime: frontStartTime,
          frontEndTime: frontEndTime,
          balanceStartTime: balanceStartTime,
          balanceEndTime: balanceEndTime,
          deliverDate: deliverTime,
          deliverTime: tempData.deliveryTime,
        },
        balancePrice: balancePrice,
      })
    })
  },
  // 预订完善订单
  toPayAdvanceSell: function () {
    const that = this
    if (that.data.advanceSellInfo.advanceAmount !== 0) {
      const loginStatus = this.checkAuth()
      if (loginStatus && that.data.productNum != '' && that.data.productNum != 0) {
        try {
          let goodsPrice = this.data.advanceSellInfo.frontPrice * that.data.productNum
          let advanceSell = {
            allPrice: goodsPrice,
            storeId: this.data.storeId,
            goodsList: [],
            orderType: 'advanceSell',
            balanceEndTime: that.data.advanceSellInfo.balanceEndTime,
            deliveryTime: that.data.advanceSellInfo.deliveryTime,
            payType: that.data.advanceSellInfo.payType,
            shipmentType: that.data.advanceSellInfo.shipmentType,
            scource: 'BUYNOW'
          }
          let productsList = this.data.goodsList
          console.log(this.data.goodsList)
          let sellPrice = this.data.advanceSellInfo.frontPrice * that.data.productNum
          productsList.forEach(item => {
            item = {
              ...item,
              productId: item.id,
              productNum: that.data.productNum,
              advanceId: that.data.advanceSellInfo.advanceId,
              balanceTotal: that.data.advanceSellInfo.balancePrice,
              sellPrice: sellPrice
            }
            console.log(item)
            advanceSell.goodsList.push(item)
          })
          console.log(advanceSell)
          wx.setStorageSync('wj_shopcart', advanceSell)
        } catch (e) {}
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../order/perfectOrder/perfectOrder'
          })
        } else {
          that.handlePopupPhone()
        }
      } else {

      }
    } else {
      wx.showToast({
        title: '您来晚了，已经卖完了~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 获取缓存的用户信息
  getMemberUserInfo: function () {
    const that = this
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: "您还未授权，请登陆授权",
        icon: 'none',
        duration: 2000
      })
    } else {
      try {
        const tokens = auth.getTokens();
        if (new Date().getTime() < tokens.refreshExpiresTo) {
          let user = app.globalData.userInfo
          console.log(user)
          that.setData({
            userInfo: user.wxaUser,
            hasUserInfo: true,
          })
        } else {
          // accessTokens 过期 需要重新登录
          that.setData({
            hasUserInfo: false
          })
        }
      } catch (error) {

      }
    }
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})